import { Image, StyleSheet, Text, View } from "react-native";
import React, { useCallback, useEffect, useState } from "react";
import { SafeAreaView } from "react-native-safe-area-context";
import Head from "../../components/Head";
import { AntDesign } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import { Button, Checkbox } from "react-native-paper";
import RecommendList from "../../components/RecommendList";
import { RefreshControl, ScrollView } from "react-native-gesture-handler";
import { Https } from "../../api";
import { ShoppingCarList, ShoppingCarListDataItem } from "../../types";
const RecommendListConfig = {
  sceneId: "gwc102",
  returnCount: 30,
  sceneType: 2,
  sourceId: 31,
};

const ShoppingCar = () => {
  const [checked, setChecked] = useState<boolean>(false);
  const [shoppingCarList, setShoppingCarList] =
    useState<ShoppingCarListDataItem[]>();
  const [allPrice, setAllPrice] = useState<number>(0);
  const [shoppingCount, setShoppingCount] = useState<number>(0);
  const [checkList, setCheckList] = useState<Array<string>>([]);
  const navigation = useNavigation();
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    findShoppingCar();
  }, []);

  useEffect(() => {
    setAllPrice(0);
    setShoppingCount(0);
    setChecked(checkList.length === shoppingCarList?.length);
    let allPrice = 0;
    let shoppingCount = 0;
    checkList.forEach((item) => {
      const result = shoppingCarList?.filter(({ _id }) => _id === item);
      if (result) {
        const { addPrice, quantity } = result[0];
        allPrice += addPrice * quantity;
        shoppingCount += quantity;
      }
    });
    setAllPrice(allPrice);
    setShoppingCount(shoppingCount);
  }, [checkList]);

  const findShoppingCar = async () => {
    const { data, success }: ShoppingCarList = await Https.findShoppingCar();
    if (success) {
      setShoppingCarList(data);
    }
  };

  //下拉刷新
  const wait = () => {
    return new Promise((resolve) => {
      findShoppingCar().then(resolve);
    });
  };
  //下拉刷新
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    // setProductList([]);
    wait().then(() => setRefreshing(false));
  }, []);

  const handleCheckboxPress = (id: string) => {
    const result = checkList.indexOf(id);
    console.log(checkList.length);
    if (result > -1) {
      setCheckList(checkList.filter((item) => item !== id));
      return;
    }

    setCheckList([id, ...checkList]);

    console.log(checkList.length === shoppingCarList?.length);
  };

  const handleAllChecked = () => {
    setChecked(!checked);
    if (!checked) {
      let arr: Array<string> = [];
      shoppingCarList?.forEach(({ _id }) => {
        arr.push(_id);
      });
      setCheckList(arr);
      return;
    }
    setCheckList([]);
  };
  return (
    <SafeAreaView style={{ backgroundColor: "#fff", flex: 1 }}>
      <Head />
      <View
        style={{ backgroundColor: "#f2f2f2", flex: 1, position: "relative" }}
      >
        <ScrollView
          showsVerticalScrollIndicator={false}
          keyboardDismissMode={"on-drag"}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={onRefresh}
              title="下拉刷新"
            />
          }
        >
          {/* 空状态组件 */}
          {!shoppingCarList && (
            <View style={styles.empty}>
              <Image
                style={styles.emptyImg}
                source={require("../../assets/images/ShoppingCar.png")}
              />
              <Text style={styles.emptyText}>亲，您还没有添加购物清单</Text>
            </View>
          )}
          {shoppingCarList &&
            shoppingCarList.map(
              (
                {
                  gscPicmainPath,
                  goodsName,
                  colorName,
                  goodsCode,
                  quantity,
                  addPrice,
                  sizeName,
                  _id,
                }
              ) => (
                <View style={styles.commoditySynopsis} key={_id}>
                  <Checkbox.Android
                    uncheckedColor="#000"
                    color="#000"
                    status={
                      checkList.some((item) => item === _id)
                        ? "checked"
                        : "unchecked"
                    }
                    onPress={() => handleCheckboxPress(_id)}
                  />
                  <Image
                    resizeMode="contain"
                    style={styles.commodityImg}
                    source={{
                      uri: gscPicmainPath,
                    }}
                  />
                  <View style={styles.commodityInfo}>
                    <Text numberOfLines={1}>{goodsName}</Text>
                    <View style={styles.commoditySize}>
                      <Text
                        numberOfLines={1}
                      >{`${sizeName} / ${colorName}`}</Text>
                      <AntDesign name="caretdown" size={8} color="black" />
                    </View>
                    <Text style={{ color: "#b4b4b4" }}>
                      商品编号：{goodsCode}
                    </Text>
                    <View style={styles.commodityPrice}>
                      <View style={styles.alignCenter}>
                        <Text style={{ ...styles.textColor, fontSize: 10 }}>
                          ￥
                        </Text>
                        <Text style={{ ...styles.textColor, fontSize: 20 }}>
                          {addPrice}
                        </Text>
                      </View>
                      <Text style={styles.commodityCount}>x{quantity}</Text>
                    </View>
                  </View>
                </View>
              )
            )}
          <RecommendList {...RecommendListConfig} />
        </ScrollView>
        <View
          style={{
            ...styles.calculate,
            ...styles.alignCenter,
            justifyContent: "space-between",
          }}
        >
          <View style={styles.alignCenter}>
            <Checkbox.Android
              uncheckedColor="#000"
              color="#000"
              status={checked ? "checked" : "unchecked"}
              onPress={handleAllChecked}
            />
            <Text style={{ fontWeight: "600" }}>全选</Text>
          </View>
          <View
            style={{
              ...styles.alignCenter,
              justifyContent: "space-evenly",
              flex: 1,
            }}
          >
            <Text style={{ fontWeight: "600" }}>共 {shoppingCount} 件</Text>
            <Text style={{ fontWeight: "600" }}>合计 ￥ {allPrice} </Text>
          </View>
          <Button
            mode="contained"
            textColor="#fff"
            buttonColor="#000"
            style={{ borderRadius: 0, padding: 5, width: 110 }}
            compact={true}
            onPress={() => {}}
          >
            购买结算
          </Button>
        </View>
      </View>
    </SafeAreaView>
  );
};

export default ShoppingCar;

const styles = StyleSheet.create({
  justify: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    width: "100%",
  },
  alignCenter: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
  },
  textColor: {
    color: "red",
    fontWeight: "600",
  },
  empty: {
    height: 500,
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  emptyImg: {
    width: 200,
    height: 200,
  },
  emptyText: {
    color: "#cfd3e4",
  },
  iosCheckbox: {
    width: 25,
    height: 25,
    marginLeft: 10,
    borderRadius: 5,
    borderWidth: 2,
    borderColor: "#000",
  },
  commoditySynopsis: {
    width: "95%",
    height: 150,
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    marginLeft: "2.5%",
    marginTop: 30,
    paddingHorizontal: 10,
    borderRadius: 10,
    backgroundColor: "#fff",
  },
  commodityImg: {
    width: 100,
    height: 130,
    // borderWidth: 1,
    borderColor: "#000",
    borderRadius: 10,
  },
  commodityInfo: {
    flex: 1,
    height: 110,
    display: "flex",

    flexDirection: "column",
    justifyContent: "space-between",
  },
  commoditySize: {
    width: 150,
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    padding: 5,
    borderRadius: 5,
    backgroundColor: "#eeeeee",
  },
  commodityPrice: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
  },
  commodityCount: {
    // width: 25,
    // height: 25,
    paddingHorizontal: 5,
    paddingVertical: 3,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: "#eaeaea",
  },
  calculate: {
    position: "absolute",
    bottom: 0,
    left: 0,
    height: 50,
    width: "100%",
    backgroundColor: "#fff",
  },
});
